package com.yoke.controller.weixin;

import com.alibaba.fastjson.JSONArray;
import com.yoke.common.JsonMessage;
import com.yoke.common.base.NginxBaseControl;
import com.yoke.common.tools.UrlPath;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.EncryptUtil;
import com.yoke.util.FileUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/5/19.
 */
@Controller
@RequestMapping("weixin")
public class WeiXinControl extends NginxBaseControl {

    @RequestMapping(value = "index.html", produces = MediaType.TEXT_HTML_VALUE)
    public String index() throws IOException {
        JSONArray jsonArray = UrlPath.start(getConfPath(), UrlPath.Type.WeiXin);
        request.setAttribute("array", jsonArray);
        return "weixin/index";
    }


    @RequestMapping(value = "save_weixin.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_weixin(String context, String tag) {
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                return JsonMessage.getString(100, "保存失败,文件不存在，请联系管理员");
            }
            String weixinContext = FileUtil.readToString(file);
            if (StringUtil.IsEmpty(weixinContext)) {
                return JsonMessage.getString(100, "保存失败,文件内容为null，请联系管理员");
            }
            int s = weixinContext.indexOf("<!--weixin-->");
            int e = weixinContext.indexOf("<!--weixin_end-->");
            if (e < s) {
                return JsonMessage.getString(100, "保存失败,文件内容异常，请联系管理员");
            }
            String[] wx = StringUtil.StringToArray(context);
            if (wx == null || wx.length < 1)
                return JsonMessage.getString(100, "请输入微信号");
            StringBuilder newsWeiXin = new StringBuilder("[");
            for (String item : wx) {
                if (newsWeiXin.length() > 1)
                    newsWeiXin.append(", ");
                newsWeiXin.append("\"").append(item).append("\"");
            }
            newsWeiXin.append("]");
            String vlist = weixinContext.substring(s, e + 17);

            int s_ = vlist.indexOf("[");
            int e_ = vlist.lastIndexOf("]");
            String oldVlist = vlist.substring(s_, e_ + 1);
            if (newsWeiXin.toString().equals(oldVlist)) {
                return JsonMessage.getString(200, "保存ok");
            }
            StringBuilder stringBuffer = new StringBuilder(vlist);
            stringBuffer.delete(s_, e_ + 1);
            stringBuffer.insert(s_, newsWeiXin.toString());
            StringBuffer file_context = new StringBuffer(weixinContext);
            file_context.delete(s, e + 17);
            file_context.insert(s, stringBuffer);
            FileUtil.writeFile(file.getPath(), file_context);
            return JsonMessage.getString(200, "保存成功");
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("微信保存失败", e);
            return JsonMessage.getString(100, "保存失败,操作异常，请联系管理员：" + e.getLocalizedMessage());
        }
    }

    /**
     * @param tag
     * @return
     */
    @RequestMapping(value = "edit_{tag}.html", produces = MediaType.TEXT_HTML_VALUE)
    public String edit(@PathVariable String tag) {
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                request.setAttribute("tip", "编辑失败,文件不存在，请联系管理员");
                return "weixin/edit";
            }
            String weixinContext = FileUtil.readToString(file);
            if (StringUtil.IsEmpty(weixinContext)) {
                request.setAttribute("tip", "编辑失败,文件内容为null，请联系管理员");
                return "weixin/edit";
            }
            int s = weixinContext.indexOf("<!--weixin-->");
            int e = weixinContext.indexOf("<!--weixin_end-->");
            if (e > s) {
                String vlist = weixinContext.substring(s + 13, e);
                s = vlist.indexOf("[");
                e = vlist.lastIndexOf("]");
                vlist = vlist.substring(s + 1, e);
                String[] v = StringUtil.StringToArray(vlist);
                StringBuilder vStr = new StringBuilder();
                for (String item : v) {
                    if (item.startsWith("\"") && item.endsWith("\"")) {
                        if (vStr.length() > 1)
                            vStr.append(System.lineSeparator());
                        vStr.append(item.substring(1, item.length() - 1));
                    }
                }
                request.setAttribute("tag_", tag);
                request.setAttribute("vStr", vStr.toString());
            }
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            //return JsonMessage.getString(123, );
            request.setAttribute("tip", "编辑失败,参数错误，请联系管理员:" + e.getLocalizedMessage());
            return "weixin/edit";
        }
        return "weixin/edit";
    }
}
